package com.example.music.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 下载
 *
 * @author yzh
 * @date 2023/04/11
 */
public class download implements Runnable {
    //信号类
    /*Semaphore semaphore = new Semaphore(10);*/

    private String htmlurl;
    private String path;

    public download(String htmlurl, String path) {
        this.htmlurl = htmlurl;
        this.path = path;
    }

    @Override
    public void run() {
        try {
            /*semaphore.acquire();*/
            URL url = new URL(htmlurl);

            //读的通道，拿到文件并放进通道
            ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
            url.openConnection().getConnectTimeout();
            //输出流
            FileOutputStream fileOutputStream = new FileOutputStream(path);

            //写的通道，通过transferFrom拷贝，将文件从readableByteChannel通道拷贝出去"D:\\2.mp4"
            fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
            fileOutputStream.close();
            readableByteChannel.close();
            /*semaphore.release();*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
